// 基于axios 封装的请求模块

import axios from 'axios'
import JSONbig from 'json-bigint'
import router from '@/router'


const request = axios.create({
  baseURL: 'http://api-toutiao-web.itheima.net/',
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
    try {
      return JSONbig.parse(data)
    } catch (error) {

    }
    return data;
  }],
})


// 请求拦截器
request.interceptors.request.use(function (config) {
  // config 是当前请求相关的配置信息对象
  const user = JSON.parse(localStorage.getItem('user'))
  if (user) {
    config.headers.Authorization = `Bearer ${user.token}`
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

// 响应拦截器
// Add a response interceptor
request.interceptors.response.use(function (response) {

  return response;
}, function (error) {
  const status = error.response.status
  if (status === 401) {
    //跳转到登录页面
    //清除本地存储中的用户登录状态
    window.localStorage.removeItem('user')
    router.push('/login')
  } else if (status === 403) {
    // 没有权限

  } else if (status === 400) {
    // 客户端参数错误

  } else if (status >= 500) {
    //服务端错误
  }

  return Promise.reject(error);
});

export default request
